package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.MessageParentBean;
import one.bugu.android.demon.bean.WarnBean;
import one.bugu.android.demon.bean.WarnDataBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.wallet.AccountActivity;
import one.bugu.android.demon.ui.adapter.WarnAdapter;
import one.bugu.android.demon.ui.dialog.DialogHint;
import one.bugu.android.demon.ui.dialog.DialogReward;
import one.bugu.android.demon.ui.refresh.SmartRefreshLayout;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshListener;
import one.bugu.android.demon.ui.refresh.listener.RefreshLayout;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.IsInternetUtil;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * PackageName: one.bugu.android.demon.ui.activity
 * Content: 预警界面
 *
 * @author Administrator
 * @date 2018/12/8 17:30
 */
@LKContentView(R.layout.fragment_warn)
public class WarnActivity extends MyBaseActivity {

    /**
     * 占位VIew
     */
    @LKInjectView(R.id.btbv_warn_top_bar)
    private BaseTopBarView btbv_warn_top_bar;

    @LKInjectView(R.id.ll_top_bar)
    private LinearLayout ll_top_bar;

    /**
     * 预警信息列表
     */
    @LKInjectView(R.id.addWarn_listview)
    private ListView listView;

    /**
     * 无网络是显示的内容
     */
    @LKInjectView(R.id.loadfailure)
    private LinearLayout loadfailure;

    /**
     * 无数据缺省图
     */
    @LKInjectView(R.id.rl_home_no_data)
    private RelativeLayout homeNoData;

    /**
     * 无数据添加按钮
     */
    @LKInjectView(R.id.iv_home_add)
    private ImageView homeAddIcon;

    private WarnAdapter warnAdapter;

    private View footView;

    /**
     * 无网络时 点击重试按钮
     */
    @LKInjectView(R.id.btn_failure)
    private Button btnFailure;

    @LKInjectView(R.id.ref_layout)
    private SmartRefreshLayout ref_layout;

    /**
     * 弹框
     */
    private DialogHint dialogHint;

    private DialogReward dialogReward;

    private MessageParentBean bgtInfoBeans;

    /**
     * 点击添加文字
     */
    TextView textView;

    @Override
    public void initView() {
        super.initView();
        //解决fragment嵌套出现状态栏异常问题
        StatusBarUtils.getInstance().setStatusBar("#FFFFFF", this, ll_top_bar, false);
        //初始化删除弹窗
        dialogHint = new DialogHint(this, "删除后您设置的数据将全部清空", true);
        dialogHint.setCancleText("我在想想");
        dialogHint.setOkText("确定删除");
        //底部加号布局
        LayoutInflater infla = LayoutInflater.from(this);
        footView = infla.inflate(R.layout.activity_footerview, null);
        ImageView imageView = footView.findViewById(R.id.main_add);
        textView = footView.findViewById(R.id.txt_add);
        //初始化adapter
        warnAdapter = new WarnAdapter(this, this);
        listView.setAdapter(warnAdapter);
        //点击添加, 跳转添加币界面
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentUtils.startAtyForResult(WarnActivity.this, AddCoinActivity.class, 1001);
            }
        });

        ref_layout.setEnableRefresh(true);//启用刷新
        ref_layout.setEnableLoadmore(false);//启用加载
    }

    @Override
    protected void initData() {
        super.initData();
        //检测是否有网络
        if (IsInternetUtil.isNetworkAvailable(this)) {
            listView.setVisibility(View.VISIBLE);
            loadfailure.setVisibility(View.GONE);
            getRMBRate();
            getInfo();
        } else {
            loadfailure.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //数据改变后刷新数据
        if (requestCode == 1001) {
            initData();
        }
    }

    /**
     * 获取预警信息
     */
    public void getInfo() {
        String token = PreferencesUtil.getInstance().getString(WarnActivity.this, Constant.TOKEN);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        LKUtil.getHttpManager().postBody(HttpConstant.INDEX_URL, map, ahandler);
    }

    /**
     * 获取预警信息的网络请求
     */
    @SuppressLint("HandlerLeak")
    public final BaseHttpAsycResponceHandler<WarnDataBean> ahandler = new BaseHttpAsycResponceHandler<WarnDataBean>() {
        @Override
        public void onSuccess(WarnDataBean dataBean) {
            super.onSuccess(dataBean);
            ref_layout.finishRefresh();
            List<WarnBean> infoList = dataBean.getData();
            Map<String, Double> btcEthPriceData = dataBean.getBtcEthPriceData();
            Map<String, Object> priceRatio = dataBean.getPriceRatio();
            if (infoList != null && !infoList.isEmpty()) {
                for (int i = 0; i < infoList.size(); i++) {
                    //如果交易对后relativeTrade不为USDT 设置relativePrice
                    if (!infoList.get(i).getRelativeTrade().equals("USDT")) {
                        Double relativePrice = btcEthPriceData.get(infoList.get(i).getPlatformId() + infoList.get(i).getRelativeTrade());
                        infoList.get(i).setRelativePrice(relativePrice);
                    }
                    if (infoList.get(i).getPriceUpRatio().equals("0.0")
                            && infoList.get(i).getPriceUpRatio() != null
                            && !infoList.get(i).getPriceUpRatio().isEmpty()) {
                        if (priceRatio != null && !priceRatio.isEmpty()) {
                            Object openPrice = priceRatio.get(infoList.get(i).getPlatformId() + "_" + infoList.get(i).getCoinId() + "_" + infoList.get(i).getRelativeTrade());
                            if (openPrice != null) {
                                infoList.get(i).setOpenPrice(openPrice.toString());
                            }
                        }
                    }
                }
            }
            listView.removeFooterView(footView);
            //如果返回数据为空  显示点击添加文字
            if (infoList == null || infoList.isEmpty()) {
                ref_layout.setVisibility(View.GONE);
                homeNoData.setVisibility(View.VISIBLE);
            } else {
                //添加按钮
                ref_layout.setVisibility(View.VISIBLE);
                listView.addFooterView(footView, null, true);
                homeNoData.setVisibility(View.GONE);
            }
            warnAdapter.updateData(infoList);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ref_layout.finishRefresh();
        }

        @Override
        public void onError() {
            super.onError();
            ref_layout.finishRefresh();
        }
    };

    /**
     * 移除币和预警设置的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> delHandler = new BaseHttpAsycResponceHandler<String>(true) {

        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            //刷新数据
            initData();
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();

        btbv_warn_top_bar.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                //账户页面
                IntentUtils.startAty(WarnActivity.this, AccountActivity.class);
            }
        });

        //长按删除币和设置信息 弹出弹框
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                PreferencesUtil.getInstance().putString(WarnActivity.this, Constant.DELROWID, ((WarnBean) warnAdapter.getItem(i)).getAddRowId());
                dialogShow();
                return false;
            }
        });
        //无网络时 点击重试
        btnFailure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                initData();
            }
        });
        //无数据添加图片点击事件
        homeAddIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentUtils.startAtyForResult(WarnActivity.this, AddCoinActivity.class, 1001);
            }
        });

        ref_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //刷新数据
                initData();
            }
        });
    }

    /**
     * 删除弹框
     */
    private void dialogShow() {
        AlertDialog.Builder builder = new AlertDialog.Builder(WarnActivity.this);
        LayoutInflater inflater = LayoutInflater.from(WarnActivity.this);
        View v = inflater.inflate(R.layout.dialog_del, null);
        Button btn_sure = (Button) v.findViewById(R.id.dialog_ok);
        Button btn_cancel = (Button) v.findViewById(R.id.dialog_canle);
        final Dialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(v);
        //点击确认 调用删除方法
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                String delRowId = PreferencesUtil.getInstance().getString(WarnActivity.this, Constant.DELROWID);

                String token = PreferencesUtil.getInstance().getString(WarnActivity.this, Constant.TOKEN);
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                map.put("rowId", delRowId);
                LKUtil.getHttpManager().postBody(HttpConstant.DELETE_URL, map, delHandler);
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取人民币汇率
     */
    public void getRMBRate() {
        String token = PreferencesUtil.getInstance().getString(WarnActivity.this, Constant.TOKEN);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        LKUtil.getHttpManager().postBody(HttpConstant.GETRATE_URL, map, getRMBRateHanlder);
    }

    /**
     * 获取人民币汇率的网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> getRMBRateHanlder = new BaseHttpAsycResponceHandler<String>() {

        public void onSuccess(String data) {
            super.onSuccess(data);
            //存储人民币汇率
            warnAdapter.setRmbPrice(data);

        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    /**
     * 页面销毁  停止刷新
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
